package com.edais.actions;

import com.edais.domain.*;
import com.edais.domain.sina.City;
import com.edais.domain.sina.Province;
import com.edais.log.IpLog;
import com.edais.service.CenterService;
import com.edais.service.OptionService;
import com.edais.service.RiskEvaluationService;
import com.edais.service.UserService;
import com.edais.service.sina.SinaHostingService;
import com.edais.util.*;
import com.edais.vo.UserBankCardVo;
import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** 设置action */
@Controller
@RequestMapping("/options")

public class OptionsAction  implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 7341359048038656711L;

	/** 日志 */
	private static final Log logger = LogFactory.getLog(OptionsAction.class);

	/** 设置service */
	@Autowired
	private OptionService optionsService;

	/** 用户service */
	@Autowired
	private UserService userService;

	@Autowired
	private FastDFSUtil fastDFSUtil;
	
	@Autowired
	private SinaHostingService sinaHostingService;
	
	@Autowired
	private CenterService centerService;

	@Autowired
	private RiskEvaluationService riskEvaluationService;
	
	
	/**
	 * 获取当前操作系统对应的应用的最新版本信息。
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAppVersionInfo")
	public void getAppVersionInfo(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		try {
			/** 接收参数(不加密) */
			String appVersion = request.getParameter("appVersion");// 客户端当前应用版本号，例如：1.1.0
			String osName = request.getParameter("osName");// 操作系统，取值范围：android、ios
			
			/** 接收参数(加密) */
//			Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
//			String appVersion = paramsMap.get("appVersion");   // 客户端当前应用版本号，例如：1.1.0
//			String osName = paramsMap.get("osName");   // 操作系统，取值范围：android、ios
			
			
			/** 非空校验 */
			// 版本号非空校验
			if (StringUtils.isBlank(appVersion)) {
				logger.debug("options/getAppVersionInfo 版本号为空");
				jsonMap.put("rescode", Consts.CHECK_CODE);
				jsonMap.put("resmsg", Consts.ErrorMsg.MSG00024);
				jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.APP_VERSION_IS_NULL);
				/** 处理返回结果 */
				String result = JsonUtil.getJsonStringFromMap(jsonMap);
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}
			// 操作系统非空校验
			if (StringUtils.isBlank(osName)) {
				logger.debug("options/getAppVersionInfo 操作系统为空");
				jsonMap.put("rescode", Consts.CHECK_CODE);
				jsonMap.put("resmsg", Consts.ErrorMsg.MSG00026);
				jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.OS_NAME_IS_NULL);
				/** 处理返回结果 */
				String result = JsonUtil.getJsonStringFromMap(jsonMap);
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}
			
			/** 根据应用版本号、操作系统查询该版本的信息 */
			AppVersionInfo appVersionInfo = this.optionsService
					.getAppVersionInfo(appVersion, osName);
			logger.info(appVersionInfo.getAppVersion());

			jsonMap.put("downloadUrl", appVersionInfo.getDownloadUrl());
			jsonMap.put("updateDesc", appVersionInfo.getUpdateDesc());
			jsonMap.put("updateType", appVersionInfo.getUpdateType());// 更新类型：1-无需升级，2-可选升级,3-必须升级
			jsonMap.put("inreview", appVersionInfo.getInreview());
			jsonMap.put("readyforsale", appVersionInfo.getReadyforsale());
			jsonMap.put("appVersion", appVersionInfo.getAppVersion());

			jsonMap.put("rescode", Consts.SUCCESS_CODE);
			jsonMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
			jsonMap.put("resmsg_cn", "");
			/** 处理返回结果 */
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		} catch (Exception e) {
			logger.error("options/getAppVersionInfo 异常:" + e.getMessage());
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			/** 处理返回结果 */
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
	}

	/**
	 * E400029 下载应用程序（android） (不用)
	 * 
	 * @param request
	 * @return
	 * @throws ActionException
	 */
	@RequestMapping(value = "/downloadApp")
	public void downloadApp(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String data = "";
		try {
			/** 接收参数 */
			// 下载地址URL，例如：group1/M00/00/E6/rBEiZlPXAiLig5qnAJZkyzh-krA103.apk
			String url = request.getParameter("url");

			byte[] buf = this.fastDFSUtil.download(url);
			if (buf == null) {
				logger.debug("======下载应用发生异常======");
				logger.debug("======/options/downloadApp ======");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			} else {
				logger.debug("/options/downloadApp 应用路径为：" + url);
				data = new String(buf, "UTF8");
			}
			logger.info(buf.length);

			jsonMap.put("data", data);
//			String result = CommonUtil.setResultInfo(jsonMap,
//					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
//			// 处理返回结果
//			CommonUtil.responseJson(result, response);
//
//			response.setCharacterEncoding("utf-8");

			// 保存窗口中显示的文件名
			String fileName = "鼓钱包" + ".apk";
			fileName = URLEncoder.encode(fileName, "UTF-8");
			response.reset();
			// 设置内容类型
			response.setContentType("application/vnd.android");
			// response.setContentType("APPLICATION/OCTET-STREAM");
			// response.setContentType("text/html; charset=utf-8");
			if (fileName.length() > 150) {
				String guessCharset = "gb2312";
				/** 根据request的locale 得出可能的编码，中文操作系统通常是gb2312 */
				fileName = new String(fileName.getBytes(guessCharset),
						"ISO8859-1");
			}
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ fileName + "\"");
			OutputStream out = response.getOutputStream();
			out.write(buf);
			//response.setStatus(response.SC_OK);
			response.flushBuffer();
			out.close();

		} catch (Exception e) {
			logger.error("/options/downloadApp 异常" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	

	/**
	 * 绑卡卡号预处理
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/setPayBankFirst")
	public void setPayBankFirst(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id
//		String bankID = paramsMap.get("bankID");// 选择的银行id
//		String bankCardNM = paramsMap.get("bankCardNM");// 回款卡号
//		
//		String phoneNo = paramsMap.get("phoneNo");//银行预留手机号
//		String provinceId = paramsMap.get("provinceId");//省份
//		String cityId = paramsMap.get("cityId");//城市
		String setupFlag = paramsMap.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
		
		String ip = CommonUtil.getClientIP(request);
		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("绑定银行卡");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);

		if("2".equals(setupFlag)){
			logBean.setDetail(userId+"在APP端进行了绑卡操作");
		}else{
			logBean.setDetail(userId+"在WEB端进行了绑卡操作");
		}

		try {
			// 参数检查
			Map<String, String> checkRes = setPayBankFirstCheck(paramsMap);
			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
				logger.error("绑卡卡号处理数据检查失败:" + checkRes.get("message"));
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkRes.get("code"),
						"", checkRes.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}
			Map<String,String> map = new HashMap<String,String>();
			map.putAll(paramsMap);
			map.putAll(checkRes);
			
			Map<String,String> resultMap = optionsService.setPayBankFirst(map);
			
			/*jsonMap.put("requestNo", resultMap.get("requestNo"));
			jsonMap.put("ticket", resultMap.get("ticket"));*/
			String result = CommonUtil.setResultStringCn(
				jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("options/setPayBankFirst 异常:" + e.getMessage());
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 绑卡卡号推进处理
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	/*@RequestMapping(value = "/setPayBankSecond")
	public void setPayBankSecond(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id
		String requestNo = paramsMap.get("requestNo");// 绑定卡id
		String ticket = paramsMap.get("ticket");// 绑卡时返回的ticket
		String validCode = paramsMap.get("valid_code");// 短信验证码
		
		String ip = CommonUtil.getClientIP(request);
		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("绑定银行卡");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);
		logBean.setDetail(userId+"在APP端进行了绑卡操作");

		try {
			// 程序必须参数未传入
			if (StringUtils.isBlank(userId) || StringUtils.isBlank(requestNo)
					|| StringUtils.isBlank(ticket)
					|| StringUtils.isBlank(validCode)) {
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE, "",
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			optionsService.setPayBankSecond(paramsMap);
			
			// 获取绑卡信息
			HashMap<String,Object> userPayCdParam = new HashMap<String,Object>();
			userPayCdParam.put("isValid","Y");
			userPayCdParam.put("userId", userId);
			userPayCdParam.put("isBinding", "Y");
			UserBankCardVo userRecePayCard =centerService.getRecePayBank(userPayCdParam);
			if (userRecePayCard == null) {
				jsonMap = BeanUtil.getMapFromBean(new UserBankCardVo());
			} else {
				jsonMap = BeanUtil.getMapFromBean(userRecePayCard);
			}
			
			logBean.setStatus(Consts.SUCCESS_CN);
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
				jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("options/setReceivedPayBank 异常:" + e.getMessage());
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}*/
	
	/**
	 * 绑卡卡号预处理数据检查
	 * @param map
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> setPayBankFirstCheck(Map<String, String> map)throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		String userId = map.get("userId");
		String setupFlag = map.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
		
		// 程序必须参数未传入
		if (StringUtils.isBlank(userId)) {
			result.put("code", Consts.ERROR_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return result;
		}
		
		// 发送标识
		if(StrUtil.setupFlagCheck(setupFlag) == false){
			logger.error("绑卡数据检查失败： 发送标识无效！发送标识:" + setupFlag);
			result.put("code", Consts.ERROR_CODE);
			result.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return result;
		}
		
		// 未選擇銀行
		if (StringUtils.isBlank(map.get("bankID"))) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BANK_IS_NULL);
			return result;
		}
		
		// 未填写卡号
		if (StringUtils.isBlank(map.get("bankCardNM"))) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BANKCARD_IS_NULL);
			return result;
		}
		
		// 未填写省份
		if (StringUtils.isBlank(map.get("provinceId"))) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.CARDPROVINCE_IS_NULL);
			return result;
		}
		
		// 未填写银行预留手机号
		if (StringUtils.isBlank(map.get("phoneNo"))) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.PHONE_NO_IS_NULL);
			return result;
		}
		
		// 银行预留手机号合法检查
		boolean mobileCheck = map.get("phoneNo").matches(Consts.PHONECHECK2);
		if (!mobileCheck) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
			return result;
		}
		
		// 未填写城市
		if (StringUtils.isBlank(map.get("cityId"))) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.CARDCITY_IS_NULL);
			return result;
		}
		
		// 实名认证检查
		User user = userService.getUserDetail(userId);

		// 是否实名认证(sina的绑定认证已通过)
		if (!"1".equals(user.getIs_create_acct()) || !"Y".equals(user.getIdcard_validate())) {
			// 没有经过实名认证不能进行购买
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.AUTHENTICATION_IS_NOT);
			return result;
		}
		
		// 绑定过卡不能再次绑定
		HashMap<String,Object> userPayCdParam = new HashMap<String,Object>();
		userPayCdParam.put("isValid","Y");
		userPayCdParam.put("userId", userId);
		userPayCdParam.put("isBinding", "Y");
		UserBankCardVo userRecePayCard =centerService.getRecePayBank(userPayCdParam);
		if(null != userRecePayCard){
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BANKCARD_IS_EXIST);
			return result;
		}

		result.put("code", Consts.SUCCESS_CODE);
		result.put("message", Consts.SUCCESS_DESCRIBE);
		return result;
	}

	

	/**
	 * 认证状态列表获取
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
//	@RequestMapping(value = "/getAuthsStatus")
//	public void getAuthsStatus(HttpServletRequest request,
//			HttpServletResponse response) {
//		Map<String, Object> jsonMap = new HashMap<String, Object>();
//		// 解密请求参数
//		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
//		String userID = paramsMap.get("userId");
//
//		if (StringUtils.isBlank(userID)) {
//			logger.debug("options/getAuthsStatus 传入参数userID为空");
//			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
//				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
//				Message.CnDescriptionExpression.BUSINESSE_ERROR);
//			CommonUtil.responseJson(result, response);
//			return;
//		}
//
//		try {
//			// 获取认证状态列表
//			User user = userService.getUserDetail(userID);
//
//			jsonMap.put("idcardValidate", user.getIdcard_validate());
//			jsonMap.put("mobileValidate", user.getMobile_validate());
//			
//			String result = CommonUtil.setResultStringCn(jsonMap,
//				Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
//				"");
//			CommonUtil.responseJson(result, response);
//		} catch (Exception e) {
//			logger.error("options/getAuthsStatus 异常:" + e.getMessage());
//			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
//				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
//				Message.CnDescriptionExpression.BUSINESSE_ERROR);
//			CommonUtil.responseJson(result, response);
//			return;
//		}
//	}

	
	
	/**
	 * ID5认证
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/authenticationSubmit")
	public void authenticationSubmit(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");
		String cardNo = paramsMap.get("identityNo");//身份证
		String name = paramsMap.get("realname");//真实姓名
		
		try{
			if (StringUtils.isBlank(userId)) {
				logger.debug("options/authenticationSubmit 传入参数userID为空");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
				return;
			}

			if (StringUtils.isBlank(cardNo)) {
				logger.debug("options/authenticationSubmit 传入参数identityNo为空");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.IDENTITYNO_IS_NULL);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			if (StringUtils.isBlank(name)) {
				logger.debug("options/authenticationSubmit 传入参数realname为空");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.REALNAME_IS_NULL);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			String identityNo = cardNo.trim();//身份证
			String realname = name.trim();//真实姓名
			
			User user = userService.getUserDetail(userId);
			// 判断该用户是否已经认证过，认证过的用户无需再一次认证
			if ("Y".equals(user.getIdcard_validate()) && 
					"1".equals(user.getIs_create_acct())) {
				logger.debug("options/authenticationSubmit 用户已经过实名认证");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.USER_HAS_REALNAMEAUTHENTICATION_OVER);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 15位身份证转成18位
	        String eightcardid;
			if (identityNo.length() == 15) {
				// 15位身份证转成18位
				eightcardid = IDCard.uptoeighteen(identityNo);
			} else {
				eightcardid = identityNo;
			}
			
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			map.put("realname", realname);
			map.put("eightcardid", eightcardid);
			map.put("identitynum", identityNo);	
			map.put("depositDockUserid", user.getDeposit_dock_userid());
			
			boolean flag = true;
			// ID5认证（设置实名信息 + 创建主账户 ）
			if(!"Y".equals(user.getIdcard_validate())){
				// 设置实名信息
				flag = sinaHostingService.setSinaRealName(map);
			}
			
			// 判断该身份证是否已经被使用，一个身份证只能用一次
			if(!flag){
				logger.error("options/authenticationSubmit 异常:" + "使用的身份证已认证");
				// 处理返回结果
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.IDCARD_USED);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			map.put("userid", userId);
			
			// 判断是否已经创建主账户
			if(!"1".equals(user.getIs_create_acct())){
				sinaHostingService.createMainAcount(map);
			}
			
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
					"");
			CommonUtil.responseJson(result, response);
		}catch (Exception e) {
			logger.error("options/authenticationSubmit 异常:" + e.getMessage());
			// 处理返回结果
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.CHECK_CODE, "",
				Message.CnDescriptionExpression.REALNAME_AUTHENTICATION_FAILED);
			CommonUtil.responseJson(result, response);
		}
	}
	/**
	 * 插入用户意见反馈
	 * */
	@RequestMapping(value = "/insertView")
	public void insertView(HttpServletRequest request,
			HttpServletResponse response) {
		int defaultLength = 200;   //反馈意见长度默认不超过200字符（不区分汉字英文）
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");
		String mobile = paramsMap.get("mobile");
		String email = paramsMap.get("email");
		String content = paramsMap.get("content");
		Integer userIdInt = null;
		if(userId!=null){
			try{
				userIdInt = Integer.parseInt(userId);
			}catch(Exception e){
				userIdInt = null;
			}
		}
		try{
			if (StringUtils.isBlank(content)) {
				logger.debug("options/insertView 传入参数content为空");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.CONTENT_IS_NULL);
				CommonUtil.responseJson(result, response);
				return;
			}
			//前台将用户输入的& = + %进行替换
			content = content.replaceAll("（equal）", "=");
			content = content.replaceAll("（and）", "&");
			content = content.replaceAll("（add）", "+");
			content = content.replaceAll("（percent）", "%");
			
//			content = java.net.URLDecoder.decode(content,"utf-8");
			if(content.length()>defaultLength){
				logger.debug("options/insertView 传入参数content超过200字符");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.CONTENT_IS_TOO_LONG);
				CommonUtil.responseJson(result, response);
				return;
			}
			if(!StringUtils.isBlank(mobile)){
				boolean flag = mobile.matches(Consts.PHONECHECK);
				if (!flag) {
					String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.CHECK_CODE, "",
						Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
					CommonUtil.responseJson(result, response);
					logger.debug("options/insertView手机号格式不对");
					return;
				}
			}
			if(!StringUtils.isBlank(email)){
				Matcher matcher2 = Pattern.compile("^(\\S+@\\S+)$").matcher(email);// 邮箱正则
				if(!matcher2.matches()){
					String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.CHECK_CODE, "",
						Message.CnDescriptionExpression.EMAIL_IS_NON_STANDARD);
					CommonUtil.responseJson(result, response);
					logger.debug("options/insertView 邮箱格式不对");
					return;
				}
			}
			
			ViewFeedBack viewMsg = new ViewFeedBack();
			viewMsg.setEmail(email);
			viewMsg.setPhoneNO(mobile);
			viewMsg.setUserId(userIdInt);
			viewMsg.setViewContent(content);
			this.optionsService.insertView(viewMsg);
			
			String result = CommonUtil.setResultStringCn(jsonMap,
				Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
				"");
			CommonUtil.responseJson(result, response);
		}catch(Exception e){
			logger.error("options/insertView 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
		return;
	}
	
	/**
	 * 推送主题开关设置
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/setPushSwitch")
	public void setPushSwitch(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");
		String onOrOff = paramsMap.get("onOrOff");//开关设置(0:off 1:on)
		String theme = paramsMap.get("theme");//开关设置对象(order_lock_time_end:封闭期已结束 credit_match_success:债权匹配成功)
		
		if(StringUtils.isBlank(userId) || 
		   StringUtils.isBlank(onOrOff) ||
		   StringUtils.isBlank(theme) || 
		   (!(("0".equals(onOrOff)) || "1".equals(onOrOff)))){
			logger.debug("options/setPushSwitch 传入用户id为空/开关参数未设置/主题未选择");
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		
		try{
			String themeId = optionsService.getThemeId(theme);
			if(StringUtils.isBlank(themeId)){
				logger.debug("options/setPushSwitch 主题ID未查询到");
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			//推送主题开关设置
			if("1".equals(onOrOff)){
				//开启(如果表中存在该用户关闭的情况下,开启开关。反之没数据和已经开启的情况无需处理)
				optionsService.setPushSwitchOn("Y",userId,"N",themeId);
			}else{
				//关闭(如果表中存在该用户开启的情况下,关闭开关。反之没数据就插入关闭信息)
				optionsService.setPushSwitchOff(userId,themeId,"N","Y");
			}
			
			String result = CommonUtil.setResultStringCn(
				jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
		}catch(Exception ex){
			logger.debug("options/setPushSwitch 异常" + ex.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	
	
	/**
	 * 取得省份和城市的基础数据
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getProvinceAndCity")
	public void getProvinceAndCity(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		try{
			// 取得省份和城市的基础数据 
			List<Province> provinceList = optionsService.getAreaData();
			
			if(provinceList == null || provinceList.size() == 0){
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
					CommonUtil.responseJson(result, response);
					return;
			}else{
				jsonMap.put("listSize", provinceList.size());
				jsonMap.put("list", provinceList);
				String result = CommonUtil.setResultStringCn(jsonMap,
						Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
						"");
					CommonUtil.responseJson(result, response);
			}
			
		} catch (Exception e) {
			logger.error("options/getProvinceAndCity 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 修改支付密码
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/modifyPayPwd")
	public void modifyPayPwd(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		
		try{
			// 数据检查
			Map<String,String> checkMap = modifyPayPwdCheck(paramsMap);
			if (null == checkMap
					|| !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkMap.get("code"),
						"", checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 更新支付密码
			String oldMdPassword = MD5.md5(paramsMap.get("oldPassword"));
			String newMdPassword = MD5.md5(paramsMap.get("newPassword"));
			paramsMap.put("oldMdPassword", oldMdPassword);
			paramsMap.put("newMdPassword", newMdPassword);
			
			optionsService.modifyPayPwd(paramsMap);
			String result = CommonUtil.setResultStringCn(jsonMap,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
					"");
				CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("options/getProvinceAndCity 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
				Message.CnDescriptionExpression.SET_PASSWORD_WRONG);
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 修改支付密码数据检查
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String,String> modifyPayPwdCheck(Map<String, String> paramsMap) throws Exception{
		Map<String, String> resMap = new HashMap<String,String>();
		
		String userId = paramsMap.get("userId");// 用户id
		String oldPassword = paramsMap.get("oldPassword");// 旧密码
		String newPassword = paramsMap.get("newPassword");// 新密码

		// 校验用户id不能为空
		if (StringUtils.isBlank(userId)) {
			logger.error("options/modifyPayPwd 用户id为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
		// 旧密码不能为空
		if (StringUtils.isBlank(oldPassword)) {
			logger.error("options/modifyPayPwd 支付原始密码为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.OLDPASSWORD_IS_NULL);
			return resMap;
		}
		
		// 新密码不能为空
		if (StringUtils.isBlank(newPassword)) {
			logger.error("options/modifyPayPwd 支付新密码为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.NEWPASSWORD_IS_NULL);
			return resMap;
		}
		
		/**
		 *  新旧密码不得一致检查
		 */
		// 获取用户的旧密码是否正确
		User user = userService.getUserDetail(userId);
		System.out.println(MD5.md5(oldPassword));
		if(!user.getPassword_cash().equals(MD5.md5(oldPassword))){
			logger.error("options/modifyPayPwd 输入的提现原始密码错误");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.OLDPASSWORD_IS_WRONG);
			return resMap;
		}
		if(user.getPassword_cash().equals(MD5.md5(newPassword))){
			logger.error("options/modifyPayPwd 设置的提现新密码与提现原始密码一致");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.SAME_NEWANDOLDPASSWORD);
			return resMap;
		}
		
		/**
		 *  与登录密码不得一致
		 */
		if(user.getPassword().equals(MD5.md5(newPassword))){
			logger.error("options/modifyPayPwd 设置的提现密码与登录密码一致");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.SAME_PASSWORD);
			return resMap;
		}
		
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}
	
	
	
	
	
	
	
	
	
	
	/**
	 * 通过原始密码，修改登陆密码
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/updatePassword")
	public void updatePassword(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");
		String oldPassword = paramsMap.get("oldPassword");
		String newPassword = paramsMap.get("newPassword");

		if (StringUtils.isBlank(userId)) {
			logger.debug("修改登陆密码：用户id为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}

		if (StringUtils.isBlank(oldPassword)) {
			logger.debug("修改登陆密码：旧密码为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.CHECK_CODE, "",
				Message.CnDescriptionExpression.OLD_PASSWORD_IS_NULL);// 请输入旧密码
			CommonUtil.responseJson(result, response);
			return;
		}

		if (StringUtils.isBlank(newPassword)) {
			logger.debug("修改登陆密码：新密码为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.CHECK_CODE, "",
				Message.CnDescriptionExpression.NEW_PASSWORD_IS_NULL);// 请输入新密码
			CommonUtil.responseJson(result, response);
			return;
		}

		try {
			// 新密码为6-20位数字或大小写字母
			boolean flag = newPassword.matches("[a-zA-Z0-9]{6,20}");
			if (!flag) {
				logger.debug("修改登陆密码： 密码不规范");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.PASSWORD_IS_NON_STANDARD);// 请输入新密码
				CommonUtil.responseJson(result, response);
				return;
			}

			// 检查用户和密码是否正确
			User user = userService.getUserDetail(userId);
			if ((user == null) || (!user.getPassword().equals(MD5.md5(oldPassword)))) {
				logger.debug("修改登陆密码： 旧密码错误");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.OLD_PASSWORD_IS_INCORRECT);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 检查用户设置的新登录密码是否与原始密码一致
			String newPasswordMd5 = MD5.md5(newPassword);
			if(newPasswordMd5.equals(user.getPassword())){
				logger.debug("修改登陆密码： 新密码与原始密码一致");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.SAME_NEWANDOLDPASSWORD);
				CommonUtil.responseJson(result, response);
				return;
			}

			// 设置新密码
			userService.resetPswById(newPasswordMd5, userId, MD5.md5(oldPassword));
			
			String result = CommonUtil.setResultStringCn(jsonMap,
				Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
				"");
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("修改登陆密码异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.SET_PASSWORD_WRONG);
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 绑定手机
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/bindingMobile")
	public void bindingMobile(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId= paramsMap.get("userId");
		String mobile = paramsMap.get("mobile");
		String setupFlag = paramsMap.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
		
		String ip = CommonUtil.getClientIP(request);
		
		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("绑定手机号");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);
		if("2".equals(setupFlag)){
			logBean.setDetail(userId+"在APP端进行了绑定手机操作");
		}else{
			logBean.setDetail(userId+"在WEB端进行了绑定手机操作");
		}
		
		if (StringUtils.isBlank(userId)) {
			logger.error("绑定手机检查失败：用户id为空");
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}

		if (StringUtils.isBlank(mobile)) {
			logger.error("绑定手机检查失败：手机号码为空");
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.CHECK_CODE, "",
				Message.CnDescriptionExpression.MOBILE_IS_NULL);
			CommonUtil.responseJson(result, response);
			return;
		}
		
		// 发送标识
		if(StrUtil.setupFlagCheck(setupFlag) == false){
			logger.error("绑定手机检查失败： 发送标识无效！发送标识:" + setupFlag);
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.CHECK_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}

		try {
			// 非法手机号检查
			boolean flag = mobile.matches(Consts.PHONECHECK);
			if (!flag) {
				logger.error("绑定手机检查失败： 非法手机号码");
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
				CommonUtil.responseJson(result, response);
				return;
			}

			// 判读用户是否存在
			User user = userService.getUserDetail(userId);

			// 绑定的手机号是否已注册
			int count = userService.phoneIsExisted(mobile);
			if (count > 0) {
				logger.error("绑定手机检查失败： 选择绑定的手机号码已注册过账户");
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.MOBILE_IS_BOUND);
				CommonUtil.responseJson(result, response);
				return;
			}

			// 手机解绑（1.0版本中无效去除sina的绑定功能）
			/*Map resultMap = optionsService.unBindingPhone(mobile, userId);
			if(!"00000".equals(resultMap.get("code")) ){
				logger.error("手机解绑发生异常");
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
				return;
			}*/
			
			// 手机绑定
			Map resultMap = optionsService.bindingPhone(mobile, userId);
			if(!"00000".equals(resultMap.get("code")) ){
				logger.error("手机绑定发生异常");
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			logBean.setStatus(Consts.SUCCESS_CN);
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			
			String result = CommonUtil.setResultStringCn(jsonMap,
				Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("绑定手机号失败:" + e.getMessage());
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}
	
	/**
	 * 设置页面初期数据获取
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getOptions")
	public void getOptions(HttpServletRequest request,
			HttpServletResponse response)  {

		String logInfo = "设置页面—getOptions ";
		logger.info(logInfo+"开始");
		//签名校验
		if (!RequestUtil.validSign(request)) {
			logger.info(logInfo+"无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}

		//token校验
		if (!RequestUtil.validToken(request)) {
			logger.info(logInfo+"无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}

		//未登录校验
		RequestHeader header = RequestUtil.decodeHeader(request);
		if (header.getUserId() == null) {
			logger.info(logInfo+"未登录");
			ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
			return;
		}

		//返回结果集map
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 请求参数
		String userId = header.getUserId().toString();
		logInfo=logInfo+userId;
		try {

//			result = depositService.queryMyAccountDetail(paramsMap);
//			JSONObject jsonObject = JSONObject.parseObject(result);
//			String accountDetail = jsonObject.getString("accountDetail");
//			JSONObject accountDetailObject = JSONObject.parseObject(accountDetail);
//			String passwordCash=accountDetailObject.getString("passwordCash");
//			accountDetailObject.put("isSetTradePWD",StringUtil.isNotEmpty(passwordCash)?"Y":"N");


			// 获取用户账户详情
			UserAccountDetail userAccountDetail = userService.getUserAccountDetail(userId);
			if (userAccountDetail==null){
                logger.info(logInfo+"用户不存在！");
                ResultDTO resultDTO = new ResultDTO<>(ResultCode.FAILED,
                        "用户不存在");
                resultDTO.setRecord(jsonMap);
                ResponseUtil.write(response,  resultDTO);
                return;
            }
			if ("1".equals(userAccountDetail.getIs_create_acct()) && "Y".equals(userAccountDetail.getIdcard_validate())) {
				// 实名认证状态
				jsonMap.put("idcardValidate", "Y");
			}else{
				jsonMap.put("idcardValidate", "N");
			}
			/**
			 * 修改实名认证用户名显示方式：“*名”.
			 * */
			StringBuffer showName=new StringBuffer();
			if(StringUtils.isNotBlank(userAccountDetail.getReal_name())){
				if(userAccountDetail.getReal_name().length()>1){
					showName.append("*").append(userAccountDetail.getReal_name().substring(1));
				}else{
					showName.append(userAccountDetail.getReal_name());
				}
			}
			
			jsonMap.put("mobileValidate", userAccountDetail.getMobile_validate()==null?"N":userAccountDetail.getMobile_validate());
			jsonMap.put("mobile", userAccountDetail.getMobile()==null?"":userAccountDetail.getMobile());
			jsonMap.put("nickName", userAccountDetail.getNick_name()==null?"":userAccountDetail.getNick_name());
			jsonMap.put("birthday", userAccountDetail.getBirthday()==null?"":userAccountDetail.getBirthday());
			jsonMap.put("gender", userAccountDetail.getGender()==null?"":userAccountDetail.getGender());
			jsonMap.put("idCard", userAccountDetail.getId_card()==null?"":userAccountDetail.getId_card());
			jsonMap.put("realName", userAccountDetail.getReal_name()==null?"":userAccountDetail.getReal_name());
			jsonMap.put("imageIconDispose", userAccountDetail.getImage_icon_dispose()==null?"":userAccountDetail.getImage_icon_dispose());
			jsonMap.put("bankId", userAccountDetail.getBank_id()==null?"":userAccountDetail.getBank_id());
			jsonMap.put("bankName", userAccountDetail.getBank_name()==null?"":userAccountDetail.getBank_name());
			jsonMap.put("cardNumber", userAccountDetail.getCard_number()==null?"":userAccountDetail.getCard_number());
			jsonMap.put("phoneNo", userAccountDetail.getPhone_no()==null?"":userAccountDetail.getPhone_no());
			jsonMap.put("accountName", userAccountDetail.getAccount_name()==null?"":userAccountDetail.getAccount_name());
			jsonMap.put("inviterInvitationCode", userAccountDetail.getInviter_invitation_code()==null?"":userAccountDetail.getInviter_invitation_code());
			jsonMap.put("showname", showName.toString());
			//帮助入口
			IcoUserFuncInfo icoFuncInfo=userService.queryIcoFuncInfo(new Long(2));
			if(icoFuncInfo!=null){
				jsonMap.put("helpWebviewUrl",icoFuncInfo.getWebview_url());
			}else{
				jsonMap.put("helpWebviewUrl","");
			}

			//用户是否设置过登录密码
			String settingPasswordFlag = "N";
			User user = userService.getUserDetail(userId);
			if(StringUtils.isNotBlank(user.getPassword())){
				settingPasswordFlag = "Y";
			}
			jsonMap.put("settingPasswordFlag", settingPasswordFlag);

			//用户是否设置过交易密码
			String isSetTradePWD="N";
			if(StringUtils.isNotBlank(user.getPassword_cash())){
				isSetTradePWD="Y";
			}
			jsonMap.put("isSetTradePWD",isSetTradePWD);

			try {//风险评估
				RiskEvaluation riskEvaluation=riskEvaluationService.getRiskEvaluationByUserId(userId);
				jsonMap.put("isRiskEvaluation",riskEvaluation.getIsRisk());
				jsonMap.put("riskType",riskEvaluation.getRiskType());
			} catch (Exception e) {
				logger.error(logInfo+"查询风险评估异常",e);
				jsonMap.put("isRiskEvaluation","N");
			}

			logger.info(logInfo+"结束");

			ResultDTO resultDTO = new ResultDTO<>(ResultCode.SUCCESS,
					Consts.SUCCESS_DESCRIBE);
			resultDTO.setRecord(jsonMap);
			ResponseUtil.write(response,  resultDTO);

		} catch (Exception e) {
			logger.error(logInfo+"获取设置页面初期数据数据异常" ,e);
			ResultDTO resultDTO = new ResultDTO<>(ResultCode.FAILED,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			resultDTO.setRecord(jsonMap);
			ResponseUtil.write(response,  resultDTO);
			return;
		}
	}
	
	/**
	 * 借款申请
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/loanApplication")
	public void loanApplication(HttpServletRequest request,
			HttpServletResponse response) {

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		
		try {
			Map<String,String> checkMap = loanApplicationCheck(paramsMap);
			if (null == checkMap
					|| !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkMap.get("code"),
						"", checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 借款申请主处理
			String result = optionsService.addLoanApplication(paramsMap);
			
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("借款申请异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}
	
	/**
	 * 借款申请请求
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String,String> loanApplicationCheck(Map<String, String> paramsMap) throws Exception{
		Map<String, String> resMap = new HashMap<String,String>();
		String userId = paramsMap.get("userId");
		String city = paramsMap.get("city");// 所在城市
		String realName = paramsMap.get("realName");// 真实姓名
		String phone = paramsMap.get("phone");//联系电话
		String gender = paramsMap.get("gender");// 称谓(性别)（MALE:男;FEMALE:女）
		String marriageStatus = paramsMap.get("marriageStatus");// 婚姻状况(MARRIED:已婚;UNMARRIED:未婚;DIVORCE:离异;LOST:丧偶;)
		String loanAmount = paramsMap.get("loanAmount");// 借款金额
		String loanMonths = paramsMap.get("loanMonths");// 借款期限
		String borrowType = paramsMap.get("borrowType");// 借款用途描述
		
		if (StringUtils.isBlank(userId)) {
			logger.error("借款申请请求数据检查失败：用户id为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
		if (StringUtils.isBlank(city)) {
			logger.error("借款申请请求数据检查失败： 所在城市为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.CITY_IS_NULL);
			return resMap;
		}
		if (StringUtils.isBlank(realName)) {
			logger.error("借款申请请求数据检查失败： 真实姓名为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.NAME_IS_NULL);
			return resMap;
		}
		if (StringUtils.isBlank(phone)) {
			logger.error("借款申请请求数据检查失败： 联系电话为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.PHONE_IS_NULL);
			return resMap;
		}
		if (StringUtils.isBlank(loanAmount)) {
			logger.error("借款申请请求数据检查失败： 借款金额为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.LOANAMOUNT_IS_NULL);
			return resMap;
		}
		if (StringUtils.isBlank(loanMonths)) {
			logger.error("借款申请请求数据检查失败： 借款期限为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.LOANMONTHS_IS_NULL);
			return resMap;
		}
		if (StringUtils.isBlank(borrowType)) {
			logger.error("借款申请请求数据检查失败：借款用途描述为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BORROWTYPE_IS_NULL);
			return resMap;
		}
		
		if(StringUtils.isBlank(gender) || (!"MALE".equals(gender) && !"FEMALE".equals(gender))){
			logger.error("借款申请请求数据检查失败：称谓格式错误！gender=" + gender);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.GENDER_IS_ERROR);
			return resMap;
		}
		
		if(StringUtils.isBlank(marriageStatus) || 
				(!"MARRIED".equals(marriageStatus) && !"UNMARRIED".equals(marriageStatus) && 
				 !"DIVORCE".equals(marriageStatus) && !"LOST".equals(marriageStatus))){
			logger.error("借款申请请求数据检查失败：婚姻状况格式错误！marriageStatus=" + marriageStatus);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.MARRIAGESTATUS_IS_ERROR);
			return resMap;
		}
		
		if(city.length() > 17 ){
			logger.error("借款申请请求数据检查失败：所在城市字数超长！len=" + city.getBytes().length);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.CITY_LENGTH_ERROR);
			return resMap;
		}
		
		if(realName.length() > 17 ){
			logger.error("借款申请请求数据检查失败：真实姓名字数超长！len=" + city.getBytes().length);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.NAME_LENGTH_ERROR);
			return resMap;
		}
		boolean flagMobile = phone.matches(Consts.PHONECHECK);
		if(!flagMobile){
			logger.error("借款申请请求数据检查失败：联系电话格式错误！phone=" + phone);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.PHONE_LENGTH_ERROR);
			return resMap;
		}
		
		boolean flag = loanAmount.matches("^[0-9]{0,14}[\\.]{0,1}[0-9]{0,2}$");
		if (!flag) {
			logger.error("借款申请请求数据检查失败：借款金额格式错误！loanAmount=" + loanAmount);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.LOANAMOUNT_IS_ERROR);
			return resMap;
		}
		
		if(borrowType.length() > 10 ){
			logger.error("借款申请请求数据检查失败：借款用途描述字数超长！len=" + borrowType.getBytes().length);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BORROWTYPE_LENGTH_ERROR);
			return resMap;
		}
		
		boolean flag2 = loanMonths.matches("^[0-9]*$");
		if (!flag2) {
			logger.error("借款申请请求数据检查失败：借款期限格式错误！loanMonths=" + loanMonths);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.LOANMONTHS_LENGTH_ERROR);
			return resMap;
		}
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}
	
	
	/**
	 * 获取省份列表
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getAllProvince")
	public void getAllProvince(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		try{
			// 取得省份和城市的基础数据 
			List<Province> provinceList = optionsService.getAllProvince();
			
			if(provinceList == null || provinceList.size() == 0){
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
					CommonUtil.responseJson(result, response);
					return;
			}else{
				jsonMap.put("listSize", provinceList.size());
				jsonMap.put("list", provinceList);
				String result = CommonUtil.setResultStringCn(jsonMap,
						Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
						"");
					CommonUtil.responseJson(result, response);
			}
			
		} catch (Exception e) {
			logger.error("options/getProvinceAndCity 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 根据省份ID查询城市列表
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getCityListByProvinceId")
	public void getCityListByProvinceId(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String provinceId = paramsMap.get("provinceId");

		if (StringUtils.isBlank(provinceId)) {
			logger.error("根据省份ID查询城市列表检查失败：省份ID为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}
		
		try{
			// 取得省份和城市的基础数据 
			List<City> cityList = this.optionsService.getCityListByProvinceId(provinceId);
			
			if(cityList == null || cityList.size() == 0){
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
					CommonUtil.responseJson(result, response);
					return;
			}else{
				jsonMap.put("listSize", cityList.size());
				jsonMap.put("list", cityList);
				String result = CommonUtil.setResultStringCn(jsonMap,
						Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
						"");
					CommonUtil.responseJson(result, response);
			}
			
		} catch (Exception e) {
			logger.error("options/getCityListByProvinceId 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 判断是否需要填写省份城市信息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/withdrawNeedProvinceAndCity")
	public void withdrawNeedProvinceAndCity(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");
		
		if (StringUtils.isBlank(userId)) {
			logger.error("判断是否需要填写省份城市信息检查失败：用户ID为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}
		try{
			boolean needProvinceAndCity = this.optionsService.withdrawNeedProvinceAndCity(userId);
			
			jsonMap.put("needProvinceAndCity", needProvinceAndCity);
			
			String result = CommonUtil.setResultStringCn(jsonMap,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
					"");
				CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("options/withdrawNeedProvinceAndCity 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}
		
	}
	
}
